<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Boost搜索引擎</title>
    <link rel="shortcut icon" href="./image/index.png" type="image/png" />
    <link rel="stylesheet" href="index.css">
</head>

<body>
    <h2 style="text-align: center;">基于One Thread One Loop式并发服务器实现Boost搜索引擎</h2>

    <div class="container">
        <div class="left-part">
            <!-- 搜索框 -->
            <div class="search">
                <input type="text" placeholder="请输入搜索关键字">
                <button onclick="Search()">搜索一下</button>
            </div>
    
            <!-- 搜索结果 -->
            <div class="result">
                
            </div>
        </div>
    
        <div class="right-part">
            <!-- 前缀搜索 -->
            <div class="prefix-search">
                <input type="text" id="prefixInput" placeholder="输入前缀，只包含英文字符">
                <button onclick="getPrefixSuggestions()">获取</button>
                <!-- 新增的容器，用于显示前缀建议 -->
                <div class="prefix-suggestions" id="prefixSuggestionsContainer"></div>
            </div>
            <!-- 热词统计 -->
            <div class="hotwords">
        
            </div>  
        </div>
    </div>

    <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
    <script>
        document.addEventListener("DOMContentLoaded", function () {
            const searchInput = document.querySelector('.search input[type="text"]');
            const searchButton = document.querySelector('.search button');

            searchInput.addEventListener('keyup', function (event) {
                if (event.key === 'Enter') {
                    searchButton.click(); // 模拟点击搜索按钮
                    event.preventDefault(); // 阻止默认行为（如表单提交）
                }
            });
        });
        document.addEventListener("DOMContentLoaded", function () {
            checkCookieAndRedirect();
        });

        function getPrefixSuggestions() {
            // 获取文本框中的值
            const prefix = $('#prefixInput').val();
            
            // 发送AJAX请求到后端
            $.ajax({
                type: "GET",
                url: "/prefix?prefixword=" + prefix,
                success: function(data) {
                    displayPrefixSuggestions(data);
                },
                error: function(xhr, status, error) {
                    alert('请检查格式，只能输入大小写字母');
                    console.error("请求失败: " + error);
                }
            });
        }

        function displayPrefixSuggestions(data) {
            // 获取显示前缀建议的容器
            const prefixSuggestionsContainer = $('#prefixSuggestionsContainer');

            // 清空容器中现有的内容
            prefixSuggestionsContainer.empty();

            // 检查data.matches是否包含数据
            if (data.matches && data.matches.length > 0) {
                // 遍历返回的数据并创建建议项
                data.matches.forEach((match) => {
                    const item = $('<div class="suggestion-item">' + match + '</div>');
                    prefixSuggestionsContainer.append(item); // 将建议项添加到容器中
                });
            } else {
                // 如果没有建议，可以添加一些提示信息
                prefixSuggestionsContainer.html("<p>没有找到匹配的前缀建议。</p>");
            }
        }

        function checkCookieAndRedirect() {
            const requiredCookieName = "SessionID"; // 假定需要检查的Cookie名称

            const cookieValue = getCookie(requiredCookieName);
            if (cookieValue == '') {
                alert('请先登录');
                // 如果Cookie不存在，则重定向到登录页面
                window.location.href = "/login.html";
            }
        }

        // 获取Cookie值的辅助函数
        function getCookie(name) {
            const cookieArr = document.cookie.split(";");

            for (let i = 0; i < cookieArr.length; i++) {
                let cookiePair = cookieArr[i].split("=");

                if (name == cookiePair[0].trim()) {
                    return decodeURIComponent(cookiePair[1]);
                }
            }
            return "";
        }

        function Search() {
            const query = $(".container .search input").val();
            $.ajax({
                type: "GET",
                url: "/s?word=" + query,
                success: data => BuildHtml(data),
            });
        }

        function BuildHtml(data) {
            const resultContainer = $(".container .result");
            resultContainer.empty();

            data.forEach((elem) => {
                const item = `
                    <div class="item">
                        <a href="${elem.url}" target="_blank">${elem.title}</a>
                        <p>${elem.desc}</p>
                        <i>${elem.url}</i>
                    </div>
                `;
                resultContainer.append(item);
            });
        }

        function renderHotWords(jsonData) {
            const hotWordsContainer = $(".hotwords");

            const hotWordsList = jsonData.hotWords.map(wordData => {
                return `<li><span>${wordData.word}</span>: ${wordData.count}</li>`;
            }).join("");

            hotWordsContainer.html(`
                <h3>热词统计</h3>
                <ul>${hotWordsList}</ul>
            `);
        }

        // 假设您通过Ajax或其他方式从服务器获取热词统计JSON数据
        $.ajax({
            type: "GET",
            url: "/hotwords",  // 替换为实际获取热词统计数据的API URL
            success: data => renderHotWords(data),
        });
    </script>
</body>

</html>